import { WXAPPID, WXAPPSECRET } from '@/config'
import { AppDataSource } from '@/config/dataSource'
import { User } from '@/entity/User'
import axios from 'axios'
import * as jwt from 'jsonwebtoken'

export class AuthService {
    private static repository = AppDataSource.getRepository(User)

    // 登录
    static async login(data: any) {
        const { code, nickName, avatar } = data

        // 1.调用微信授权接口
        const res = await axios.get(
            `https://api.weixin.qq.com/sns/jscode2session?appid=${WXAPPID}&secret=${WXAPPSECRET}&js_code=${code}&grant_type=authorization_code`
        )

        const { errcode, errmsg, session_key, openid } = res.data
        console.log(errcode, errmsg, session_key, openid)

        if (errcode) {
            throw new Error(`[${errcode}] ${errmsg}`)
        }

        // 2.查询openid对应的用户是否存在
        const userInfo = await this.repository.findOne({
            where: { openid }
            // select: ['id', 'username', 'password', 'userType'],
        })

        // 3.更新用户信息（包括新增用户/更新用户）
        const result = await this.repository.save({
            ...(userInfo || {}),
            openid: openid,
            nickName: nickName,
            avatar: avatar,
            sessionKey: session_key,
            level: userInfo?.level || 'normal'
        })

        // const { password, ...userWithoutPassword } = await this.repository.save(user);
        // // 4.生成 token
        const token = jwt.sign({ openid, session_key }, WXAPPSECRET, { expiresIn: '7d' }) // 7d

        // 5.返回用户信息

        return {
            token,
            userInfo: {
                openid: result.openid,
                nickName: result.nickName,
                avatar: result.avatar,
                level: result.level
            }
        }
    }

    // 获取用户信息
    static async getUserInfo(openid: string) {
        const user = await this.repository.findOne({
            where: { openid }
        })

        if (!user) {
            throw new Error('用户不存在')
        }

        const { openid: OPENID, ...userInfo } = user

        return userInfo
    }
}
